const CartModule = {
  state: {
    list: [],
    arr: [],
  },
  getters: {
    allChecked(state) {
      return state.list.every(prod => prod.checked)
    },
    // 合计金额
    totalMoney(state) {
      return state.list.reduce((sum, curr) => {
        if (curr.checked) {
          sum += parseFloat(curr.price) * curr.amount
        }
        return sum
      }, 0) * 1000000
    },
  },
  mutations: {
    // 加入购物车
    addToCart(state, payload) {
      // 查询购物车中是否有当前选购的商品
      const has = state.list.some(prod => prod.id === payload.id)
      // 有，则修改数量，没有则追加到购物车数组中
      if (has) {
        state.list = state.list.map(prod => {
          // 复制当前遍历到的商品对象，
          // 因为 map 遍历数组时，如果直接修改当前
          // 遍历到的商品对象，则原数组本身是会受
          // 影响的，所以为了避免这种情况，复制当前对象，
          // 修改复制后的对象信息，并返回复制对象
          const copy = { ...prod }
          if (copy.id === payload.id) {
            copy.amount += 1
          }
          return copy
        })
      } else {
        state.list.push({
          ...payload,
          amount: 1, // 商品数量默认为1
          checked: true, // 默认加入购物车的商品是被选中的
        })
      }
    },
    removeFromCart(state, payload) {
      state.list = state.list.filter(prod => prod.id !== payload.id)
    },
    modifyAmount(state, payload) {
      state.list = state.list.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.amount = payload.amount
        }
        return copy
      })
    },
    modifyChecked(state, payload) {
      state.list = state.list.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    checkedAll(state, payload) {
      state.list = state.list.map(prod => {
        const copy = { ...prod }
        copy.checked = payload.checked
        return copy
      })
    },
    addToAdress(state, payload) {
      state.arr.push({ ...payload })
    },
  },
  actions: {
    // 加入购物车向服务器发送请求
    addToCartAsync(context, payload) {
      setTimeout(() => {
        context.commit('addToCart', payload)
      }, 1000)
    },
  },
  modules: {
  },
}
export default CartModule
